import { readFileSync } from 'fs';
import glob from 'tiny-glob/sync';
import typescript from 'rollup-plugin-typescript2';

/** 当前时间 */
const now = (() => {
  const dt = new Date();
  dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset());
  return dt.toISOString().slice(0, 19).replace('T', ' ');
})();

/** 基础信息 */
const banner = (name, appid) => `
/**
 * ${name}
 * @appid ${appid}
 * @time ${now}
 */
`;

/** 插件 */
const plugins = [
  typescript({ typescript: require('typescript') }),
  {
    name: 'replace',
    renderChunk(code, chunk) {
      const originalCode = readFileSync(chunk.facadeModuleId).toString('utf-8');
      const name = originalCode.match(/(?<= @name )[^\n]+/)[0];
      const appid = originalCode.match(/(?<= @appid )\d+/)[0];
      return [banner(name, appid).trim(), code].join('\n');
    },
  },
];

// 所有爬虫
const crawlers = glob('crawlers/*.ts');

export default crawlers.map((input) => {
  const name = input.match(/([^/]+)\.ts/)[1];
  return {
    input,
    plugins,
    output: {
      file: `dist/${name}.js`,
      // format: 'esm',
      format: 'iife',
    },
  };
});
